package com.xincheng.shuimalong.util;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;

import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.dao.DaoMaster;
import com.xincheng.shuimalong.dao.DaoSession;
import com.xincheng.shuimalong.dao.HistoryChatDao;
import com.xincheng.shuimalong.entity.friend.HistoryChat;

import java.util.List;


/**
 * Created by 许浩 on 2017/7/22.
 */

public class GreenUtil {
    private DaoMaster.DevOpenHelper mHelper;
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private HistoryChatDao historyChatDao;
    private static Handler mHandler;
    private static final String DB_NAME = "shuimalong-db";
    private static GreenUtil instances;

    public static GreenUtil getInstances() {
        if (instances == null) {
            synchronized (GreenUtil.class) {
                if (instances == null) {
                    instances = new GreenUtil();
                }
            }
        }
        return instances;
    }

    /**
     * 设置greenDao
     */
    public void setDatabase(Context context) {
        // 通过 DaoMaster 的内部类 DevOpenHelper，你可以得到一个便利的 SQLiteOpenHelper 对象。
        // 可能你已经注意到了，你并不需要去编写「CREATE TABLE」这样的 SQL 语句，因为 greenDAO 已经帮你做了。
        // 注意：默认的 DaoMaster.DevOpenHelper 会在数据库升级时，删除所有的表，意味着这将导致数据的丢失。
        // 所以，在正式的项目中，你还应该做一层封装，来实现数据库的安全升级。
        mHelper = new DaoMaster.DevOpenHelper(context, DB_NAME +
                PrefUtil.getString(context, PrefKey.LOGIN_USER_ID, ""), null);
        db = mHelper.getWritableDatabase();
        // 注意：该数据库连接属于 DaoMaster，所以多个 Session 指的是相同的数据库连接。
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
        historyChatDao = mDaoSession.getHistoryChatDao();
        mHandler = new Handler();
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    public SQLiteDatabase getDb() {
        return db;
    }

    /**
     * 更新会话
     *
     * @param nick_name
     * @param face
     * @param tergid
     * @param time
     * @param lasstmessage
     * @param unbumber
     */
    public void updaConversation(String nick_name, String face, String tergid, long time, String lasstmessage, int unbumber) {
        HistoryChat chat = new HistoryChat(tergid, nick_name, face, time, lasstmessage, unbumber);
        if (hasHistory(chat.getTergid())) {
            XLog.e("更新数据库");
            historyChatDao.update(chat);
        } else {
            XLog.e("插入数据库");
            historyChatDao.insert(chat);
        }
    }

    public void updaConversation(HistoryChat chat) {
        if (hasHistory(chat.getTergid())) {
            XLog.e("更新数据库");
            historyChatDao.update(chat);
        } else {
            XLog.e("插入数据库");
            historyChatDao.insert(chat);
        }
    }

    /**
     * 获取所有会话
     *
     * @return
     */
    public void loadAll(ResultCallback<List<HistoryChat>> callback) {
        List<HistoryChat> historyChats = historyChatDao.queryBuilder().orderDesc(HistoryChatDao.Properties.Time).list();
        if (historyChats == null || historyChats.size() == 0) {
            callback.onFail("历史记录为空");
        }
        if (historyChats != null && historyChats.size() != 0) {
            callback.onCallback(historyChats);
        }
    }

    /**
     * 判断是否有会话
     *
     * @param tergid
     * @return
     */
    public boolean hasHistory(String tergid) {
        HistoryChat findchat = historyChatDao.load(tergid);
        if (findchat != null) {
            return true;
        }
        return false;
    }

    public void loadChat(String tergid, ResultCallback<HistoryChat> callback) {
        HistoryChat findchat = historyChatDao.load(tergid);
        if (findchat != null) {
            callback.onSuccess(findchat);
        } else {
            callback.onFail("本地没有记录");
        }
    }

    public void deleteHisory(String tergid) {
        if (hasHistory(tergid)) {
            historyChatDao.deleteByKey(tergid);
        }
    }

    public void deleteHisory(String tergid, ResultCallback<Boolean> callback) {
        if (hasHistory(tergid)) {
            historyChatDao.deleteByKey(tergid);
            callback.onSuccess(true);
        } else {
            callback.onFail("删除失败！");
        }
    }

    public abstract static class ResultCallback<T> {
        public ResultCallback() {
        }

        public abstract void onSuccess(T str);

        public abstract void onError(String message);

        void onFail(final String errMessage) {
            GreenUtil.mHandler.post(new Runnable() {
                public void run() {
                    ResultCallback.this.onError(errMessage);
                }
            });
        }

        void onCallback(final T t) {
            GreenUtil.mHandler.post(new Runnable() {
                public void run() {
                    ResultCallback.this.onSuccess(t);
                }
            });
        }
    }
}
